"""
Author: Meng
Date: 2018/10/13
"""
from flask_restful import Resource, reqparse
from app.api import api
from app.models.admin.config import FConfig, config_parse
from f_lib.principal.auth import admin_authority, auth_token
from f_lib.marshal_list import marshal
from f_lib.code import Msg
from app.models.safety.request_log import RequestLog
from datetime import datetime, timedelta
from f_lib.tool.time import utc_format


class LogList(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('start_time', type=str)
    parse.add_argument('end_time', type=str)
    parse.add_argument('path', type=str)
    parse.add_argument('page', type=int, default=1)
    parse.add_argument('pn', type=int, default=20)
    parse.add_argument('order', type=str, default='desc', choices=['desc', 'asc'])
    log_base = dict(
        ip=None,
        path=None,
        get_args=None,
        agent=None,
        create_time=None,
        url=None,
        username=None,
        post_args=None,
        method=None
    )

    @auth_token()
    @admin_authority
    def get(self):
        wheres = []
        arg = self.parse.parse_args()
        st = arg.get('start_time')
        et = arg.get('end_time')
        path = arg.get('path')
        page = arg.get('page', 0)
        pn = arg.get('pn', 20)
        order = arg.get('order')
        if st:
            st = utc_format(st)
        if et:
            et = utc_format(et)
        if st and et:
            wheres.append("""create_time > '{}'""".format(st))
            wheres.append("""create_time < '{}'""".format(et))
        elif st:
            wheres.append("""create_time > '{}'""".format(st))
        elif et:
            wheres.append("""create_time < '{}'""".format(et))
        else:
            t = datetime.now() - timedelta(days=30)
            wheres.append("""create_time > '{}'""".format(t.strftime('%Y-%m-%d %H:%M:%S')))
        if path:
            wheres.append("""path like '%{}%'""".format(path))
        if page is None:
            page = 0
        else:
            if page > 1:
                page = page - 1
            else:
                page = 0
        if pn is None:
            pn = 20
        else:
            if pn > 500:
                pn = 500
        log = RequestLog.query_where_many(params=list(self.log_base.keys()),
                                          wheres=wheres,
                                          limit=[page * pn, pn],
                                          order=['id', order])

        count = RequestLog.query_where_many_count(wheres=wheres)
        value = marshal(self.log_base, log)

        return Msg.success('ok', logs=value, total=count)


api.add_resource(LogList, '/log/list', endpoint='log_list')
